using System.Text.Json;
using CMS.Entity;
using CMS.Repository;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;

namespace CMS.Service.Impl;

public partial class SensitiveWordService {
    public required IMemoryCache MemoryCache { get; init; }
    public required IArticleCommentService ArticleCommentService { get; set; }

    public SensitiveWordService(IMemoryCache memoryCache,
                                ISensitiveWordRepository sensitiveWordRepository,
                                IArticleCommentService articleCommentService) : this(
        sensitiveWordRepository) {
        MemoryCache = memoryCache;
        ArticleCommentService = articleCommentService;
    }

    public async Task<(bool, string)> FilterSensitiveWords(ArticleComment articleComment) {
        var forbiddenWords = await MemoryCache.GetOrCreateAsync("Forbidden",
            async _ => await sensitiveWordRepository.Get(word => word.IsDeleted == false && word.IsForbid == true)
                                                    .ToListAsync()
        );
        if (forbiddenWords!.Any(word => articleComment.Msg!.Contains(word.WordPattern!))) {
            return (false, "含有禁用词");
        }

        var checkWords = await MemoryCache.GetOrCreateAsync("Check",
            async _ => await sensitiveWordRepository.Get(word => word.IsDeleted == false && word.IsMod == true)
                                                    .ToListAsync());
        bool haveCheck = false;
        if (checkWords!.Any(word => articleComment.Msg!.Contains(word.WordPattern!))) {
            articleComment.IsDeleted = true;
            haveCheck = true;
        }

        articleComment.CreatedDate = DateTime.Now;
        articleComment.EditDate = DateTime.Now;
        var replaceWords = await MemoryCache.GetOrCreateAsync("Replace",
            async _ => await sensitiveWordRepository
                             .Get(word => word.IsDeleted == false && word.IsMod == false && word.IsForbid == false)
                             .ToListAsync());
        foreach (SensitiveWord replaceWord in replaceWords!) {
            articleComment.Msg = articleComment.Msg!.Replace(replaceWord.WordPattern!, replaceWord.ReplaceWord);
        }

        await ArticleCommentService.AddAsync(articleComment);
        return haveCheck ? (false, "含有审查词，待审核") : (true, "成功");
    }
}